from flask import Blueprint, render_template, session, redirect, url_for, request
import os
import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from utils import load_data, save_data

customer_bp = Blueprint('customer', __name__, url_prefix='/customer')

# 数据路径统一变量
data_dir = os.path.join(os.path.dirname(__file__), 'data')
cards_path = os.path.join(data_dir, 'cards.json')
transactions_path = os.path.join(data_dir, 'transactions.json')

# ------------------------ 客户主页（导航页） ------------------------
@customer_bp.route('/dashboard', endpoint='dashboard')
def customer_dashboard():
    if session.get('role') != 'customer':
        return redirect('/login')
    return render_template('customer_dashboard.html')

# ------------------------ 1. 余额查询 ------------------------
@customer_bp.route('/balance')
def balance():
    if session.get('role') != 'customer':
        return redirect('/login')

    customer_id = session.get('user')
    cards = load_data(cards_path)
    my_cards = [card for card in cards if card['customerID'] == customer_id]
    total_balance = sum(card['balance'] for card in my_cards)

    return render_template('customer_balance.html', balance=total_balance)

# ------------------------ 2. 交易查询 ------------------------
@customer_bp.route('/transactions')
def transactions():
    if session.get('role') != 'customer':
        return redirect('/login')
    customer_id = session.get('user')

    cards = load_data(cards_path)
    card_ids = [c['cardID'] for c in cards if c['customerID'] == customer_id]
    all_transactions = load_data(transactions_path)
    customer_transactions = [t for t in all_transactions if t['cardID'] in card_ids]

    return render_template('customer_transactions.html', transactions=customer_transactions)

# ------------------------ 3. 存款 ------------------------
@customer_bp.route('/deposit', methods=['GET', 'POST'])
def deposit():
    if session.get('role') != 'customer':
        return redirect('/login')
    customer_id = session.get('user')

    cards = load_data(cards_path)
    transactions = load_data(transactions_path)
    customer_cards = [c for c in cards if c['customerID'] == customer_id]
    message = ''

    if request.method == 'POST':
        selected_card_id = request.form.get('cardID')
        amount_str = request.form.get('amount')
        card = next((c for c in customer_cards if c['cardID'] == selected_card_id), None)

        if not card:
            message = '所选银行卡无效'
        elif card.get('lost', False):
            message = '该卡已挂失，无法存款'
            transactions.append({
                "timestamp": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                "type": "存款失败",
                "amount": 0,
                "cardID": selected_card_id,
                "note": "交易失败：挂失卡尝试存款"
            })
            save_data(transactions_path, transactions)
        else:
            try:
                amount = float(amount_str)
                if amount <= 0:
                    message = '金额必须大于0'
                else:
                    card['balance'] += amount
                    save_data(cards_path, cards)
                    transactions.append({
                        "timestamp": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                        "type": "存款",
                        "amount": amount,
                        "cardID": selected_card_id,
                        "note": "客户存入现金"
                    })
                    save_data(transactions_path, transactions)
                    message = f"成功存入 {amount} 元！"
            except ValueError:
                message = '请输入有效金额'

    return render_template('customer_deposit.html', message=message, cards=customer_cards)

# ------------------------ 4. 取款 ------------------------
@customer_bp.route('/withdraw', methods=['GET', 'POST'])
def withdraw():
    if session.get('role') != 'customer':
        return redirect('/login')
    customer_id = session.get('user')

    cards = load_data(cards_path)
    transactions = load_data(transactions_path)
    customer_cards = [c for c in cards if c['customerID'] == customer_id]
    message = ''

    if request.method == 'POST':
        selected_card_id = request.form.get('cardID')
        amount_str = request.form.get('amount')
        card = next((c for c in customer_cards if c['cardID'] == selected_card_id), None)

        if not card:
            message = '所选银行卡无效'
        elif card.get('lost', False):
            message = '该卡已挂失，无法取款'
            transactions.append({
                "timestamp": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                "type": "取款失败",
                "amount": 0,
                "cardID": selected_card_id,
                "note": "交易失败：挂失卡尝试取款"
            })
            save_data(transactions_path, transactions)
        else:
            try:
                amount = float(amount_str)
                if amount <= 0:
                    message = '金额必须大于0'
                elif amount > card['balance']:
                    message = '余额不足'
                else:
                    card['balance'] -= amount
                    save_data(cards_path, cards)
                    transactions.append({
                        "timestamp": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                        "type": "取款",
                        "amount": amount,
                        "cardID": selected_card_id,
                        "note": "客户取出现金"
                    })
                    save_data(transactions_path, transactions)
                    message = f"成功取出 {amount} 元！"
            except ValueError:
                message = '请输入有效金额'

    return render_template('customer_withdraw.html', message=message, cards=customer_cards)

# ------------------------ 5. 挂失 ------------------------
@customer_bp.route('/report_lost', methods=['GET', 'POST'])
def report_lost():
    if session.get('role') != 'customer':
        return redirect('/login')

    customer_id = session.get('user')
    cards = load_data(cards_path)
    my_cards = [card for card in cards if card['customerID'] == customer_id]

    if request.method == 'POST':
        card_id = request.form['cardID']
        action = request.form.get('action')

        for card in my_cards:
            if card['cardID'] == card_id:
                card['lost'] = (action == 'report')
                break

        save_data(cards_path, cards)
        return redirect(url_for('customer.report_lost'))

    return render_template('customer_report_lost.html', cards=my_cards)

# ------------------------ 6. 修改密码 ------------------------
@customer_bp.route('/change_password', methods=['GET', 'POST'])
def change_password():
    if session.get('role') != 'customer':
        return redirect('/login')

    customer_id = session.get('user')
    cards = load_data(cards_path)
    my_cards = [card for card in cards if card['customerID'] == customer_id]

    message = ''
    success = False

    if request.method == 'POST':
        card_id = request.form['cardID']
        old_password = request.form['old_password']
        new_password = request.form['new_password']
        confirm_password = request.form['confirm_password']

        card = next((c for c in my_cards if c['cardID'] == card_id), None)
        if not card:
            message = '找不到所选银行卡'
        elif not check_password_hash(card.get('password', ''), old_password):
            message = '原密码错误'
        elif new_password != confirm_password:
            message = '两次新密码输入不一致'
        else:
            card['password'] = generate_password_hash(new_password)
            save_data(cards_path, cards)
            message = '密码修改成功！'
            success = True

    return render_template('customer_change_password.html', cards=my_cards, message=message, success=success)
# ------------------------ 7. 向管理员申请重置 ------------------------
@customer_bp.route('/request_reset_password', methods=['GET', 'POST'])
def request_reset_password():
    if session.get('role') != 'customer':
        return redirect('/login')

    customer_id = session.get('user')
    cards = load_data(cards_path)
    my_cards = [card for card in cards if card['customerID'] == customer_id]
    message = ''

    if request.method == 'POST':
        card_id = request.form['cardID']
        requests_path = os.path.join(data_dir, 'password_requests.json')
        if not os.path.exists(requests_path):
            existing_requests = []
        else:
            existing_requests = load_data(requests_path)

        # 防止重复申请
        already_pending = any(
            r['cardID'] == card_id and r['customerID'] == customer_id and r['status'] == 'pending'
            for r in existing_requests
        )

        if already_pending:
            message = '该卡密码重置申请已提交，请等待管理员处理。'
        else:
            existing_requests.append({
                "cardID": card_id,
                "customerID": customer_id,
                "status": "pending",
                "timestamp": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            })
            save_data(requests_path, existing_requests)
            message = '已成功提交密码重置申请！'

    return render_template('customer_request_reset.html', cards=my_cards, message=message)
# ------------------------ 8. 收到管理员重置密码消息 ------------------------
@customer_bp.route('/reset_status')
def reset_status():
    if session.get('role') != 'customer':
        return redirect('/login')

    customer_id = session.get('user')
    requests_path = os.path.join(data_dir, 'password_requests.json')
    if not os.path.exists(requests_path):
        requests = []
    else:
        requests = load_data(requests_path)

    my_requests = [r for r in requests if r['customerID'] == customer_id]

    return render_template('customer_reset_status.html', requests=my_requests)
